﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Liber;
using Liber.WEB;

namespace FlashQ.Main
{
    /// <summary>
    /// 普通消费者管理
    /// </summary>
    public class CustomerController:LiberController
    {
        /// <summary>
        /// 创建一个长期有效的客户端标识
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public JsonResult NewSession() {
            return Json(FnResult.Sucess(SessionID));
        }

        [HttpPost]
        public JsonResult Login() {
            string key = Request.TryGet("key", "");
            string pwd = Request.TryGet("pwd", "");

            /*前端将密码转换为16进制数字，后端进行转换并去除第一个字母_*/

            /*通过绑定的扩展帐号登录时传递open参数*/
            string opensrc = Request.TryGet("open", "");

            /*动态验证码登录时使用*/
            string captcha = Request.TryGet("captcha", "");

            FnResult<DyObject> r = null;
            if (!captcha.IsNull()) {
                /*通过动态验证码登录时*/
                var vc = Cache.Get("SMSCaptcha", "CaptchaLogin" + key);
                if (XMLSetting.DefaultSetting.First("SMS").First("Enable").Value.TryBool(false) == true && (captcha.IsNull() || vc == null || vc.ToString() != captcha)) {
                    return Json(FnResult.Failure("AcntController", "ErrCaptcha"));
                }

                r = API.NoauthorRequest("MineApp@FindAcnt")
                       .Set("mphone", key)
                       .WaitResult();
                if (!r.IsPositive) {
                    /*新用户，自动创建帐号*/
                    r = API.NoauthorRequest("MineApp@NewAcnt")
                           .Set("acnt", key)
                           .Set("mphone", key)
                           .Set("password", pwd)
                           .WaitResult();
                }
            }
            else {
                r = API.NoauthorRequest("MineApp@CheckIn")
                       .Set("key", key)
                       .Set("password", pwd.UnMD4())
                       .Set("opensrc", opensrc)
                       .WaitResult();
            }

            if (r.IsPositive) {
                SetLoginStatus(r.Data, true);
            }
            return Json(r);
        }

        /// <summary>
        /// 通过发送短信验证码验证手机号码的合法性
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult ValidatePhone(string mphone, string scene, string token) {
            if (mphone.IsNull() || scene.IsNull() || token.IsNull()) {
                return Json(FnResult<DyObject>.Failure("System", "RequiredArgs").SetError("Args", "mphone"));
            }

            if (token != mphone.MD5Encrypt_normal().Replace("-", "").ToLower()) {
                return Json(FnResult.Failure("System", "AccessDenied"));
            }

            //全局开关检查
            bool IsSMSEnable = XMLSetting.DefaultSetting.First("SMS").First("Enable").Value.TryBool(false);
            if (!IsSMSEnable) {
                return Json(FnResult.Sucess());
            }

            //限流控制[例如腾讯云，已经提供了一些限流规则，就没必要在我们这边实现]
            bool limiting = XMLSetting.DefaultSetting.First("SMS").First("Limiting").Value.TryBool(true);

            //单个会话发送间隔控制，不能少于60秒
            int tag = Cache.GetStr("SMSInterval", UID.ToString()).TryInt(0);
            if (tag > 0) {
                Log("SMSShortInterval", "", LogType.Warning);
                return Json(FnResult<DyObject>.Failure("System", "SMSShortInterval"));
            }
            else {
                Cache.Set("SMSInterval", UID.ToString(), "100", 1);
            }

            if (limiting) {
                //单个手机号码累计控制，1小时内不能超过10次
                int tag2 = Cache.GetStr("SMSMaxTimes", mphone).TryInt(0);
                if (tag2 > 10) {
                    Log("SMSMaxTimes", "", LogType.Warning);
                    return Json(FnResult<DyObject>.Failure("System", "SMSMaxTimes"));
                }
                else {
                    Cache.Set("SMSMaxTimes", mphone, (tag2 + 1).ToString(), 60);
                }
            }

            //检查已缓存的验证码
            string code = Cache.GetStr("SMSCaptcha", scene + mphone);
            if (code.IsNull()) {
                code = new Random(DateTime.Now.Millisecond).Next(100000, 900000).ToString();
            }

            Cache.Set("SMSCaptcha", scene + mphone, code, 5);

            SMS.Send(scene, new string[] { code }, mphone);
            return Json(FnResult.Sucess());
        }

        [HttpPost]
        public JsonResult SetPassword(string pwd) {
            var r = API.Request(UID, UNAME, "DemoApp@SetPassword")
                   .Set("password", pwd)
                   .WaitResult();

            return Json(r);
        }
    }
}